package com.xzmd.md_city.controller;

import com.xzmd.md_city.entity.UserInfo;
import com.xzmd.md_city.service.UserInfoService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 用户登录注册的控制器，用于连接数据库与前端网页
 */
@Controller
public class UserInfoController {
    @Resource
    private UserInfoService userInfoService;

    //  1.打开登录页
    @RequestMapping("/golog")
    public String goLogin() {
        //返回的是网页地址/templates/page/login.html
        return "page/login";
    }

    //    表示将当前的方法映射成能够在浏地址栏执行的一个动作
//    地址栏：http://localhost:8080/log
//    2.执行登录操作
    @RequestMapping("/log")
//    HttpServletRequest用于获取前端网页通过name参数传递的数据
    public String login(String username, String password, HttpSession session) {
        String info = userInfoService.findUserInfo(username, password);
        if (info.equals("ok")) {
            //返回的是网页地址/templates/page/index.html，同时将用户
            //名传回主页
            session.setAttribute("username", username);
//            System.out.println("用户:"+username);
            return "page/index";
        }
        //返回的是网页地址/templates/page/login.html
        session.setAttribute("error", info);
        return "page/login";
    }

    //    3.打开注册页
    @RequestMapping("/goreg")
    public String goReg() {
        return "page/register";
    }

    //   4.执行注册操作
    @RequestMapping("/doreg")
    public String doReg(UserInfo userInfo, Map map) {
        String info = userInfoService.saveUserInfo(userInfo);
        map.put("info",info);
        return "page/register";
    }

}
